<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>图片懒加载</title>
    <style>
        img {
            display: block;
            width: 100%;
            height: 300px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <img data-src="./img/1.jpg" alt="">
    <img data-src="./img/2.jpg" alt="">
    <img data-src="./img/3.jpg" alt="">
    <img data-src="./img/4.jpg" alt="">
    <img data-src="./img/4.jpg" alt="">
    <img data-src="./img/4.jpg" alt="">
</body>
<script>


//实现核心：一开始先不给image标签的src属性赋值 当满足 offsetTop < clientHeight+scrollTop 时再将图片的路径赋值给src
//我们可以用data-src先保留图片的初始路径
//offsetTop是元素顶部距离父元素底部的距离 如果元素无父元素 则默认的父元素为body
//scrollTop代表在有滚动条时，滚动条向下滚动的距离也就是元素顶部被遮住部分的高度。
//clientHeight代表可视区的高度
        var imgs = document.querySelectorAll('img');

        //offsetTop是元素与offsetParent的距离，循环获取直到页面顶部
        function getTop(e) {
            var T = e.offsetTop;
            while(e = e.offsetParent) {
                T += e.offsetTop;
            }
            return T;
        }

        function lazyLoad(imgs) {
            var H = document.documentElement.clientHeight;//获取可视区域高度
            var S = document.documentElement.scrollTop || document.body.scrollTop;
            for (var i = 0; i < imgs.length; i++) {
                if (H + S > getTop(imgs[i])) {
                    imgs[i].src = imgs[i].getAttribute('data-src');
                }
            }
        }

        window.onload = window.onscroll = function () { //onscroll()在滚动条滚动的时候触发
            lazyLoad(imgs);
        }
</script>
</html>